package com.niu.wm.web.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.niu.wm.model.Product;
import com.niu.wm.model.ProductCategory;
import com.niu.wm.core.ResponseObject;
import com.niu.wm.core.error.BizException;
import com.niu.wm.core.error.GlobalErrorCode;
import com.niu.wm.form.ProductSearchForm;
import com.niu.wm.vo.ProductVO;
import com.niu.wm.vo.UploadedImage;
import com.niu.wm.model.User;
import com.niu.wm.service.CategoryService;
import com.niu.wm.service.ProductService;
import com.niu.wm.service.impl.OssServiceImpl;

@Controller
@RequestMapping(value = "/product")
public class ProductController extends BaseController{
	@Autowired
	private ProductService productService;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private OssServiceImpl ossServiceImpl;
	/**
	 * 客户管理
	 * @return
	 */
	@RequestMapping(value = "/listProduct.do")
    public String listProduct(ModelMap model){
		User user = this.getCurrentUser();
		
		model.addAttribute("oss_bucketName", ossServiceImpl.getBucketName() );
		model.addAttribute("oss_endpoint", ossServiceImpl.getEndpoint() );
		
		return "product/listProduct";
	}
	
	/**
	 * 列出产品信息
	 * @return
	 */
	@RequestMapping(value = "/listData.do")
    @ResponseBody
    public Map<String, Object> listData(HttpServletRequest req,ProductSearchForm form, Pageable pager){
		User user = this.getCurrentUser();
		
		pager = this.convertPager(req, pager);
		Map<String,Object> map = new java.util.HashMap<String, Object>();
		
		int total = productService.countProduct(form);
		List<ProductVO> ls = productService.queryProduct(form, pager);
		
		map.put("total", total);
		map.put("rows", ls);
		
		return map;
	}
	
	/**
	 * 产品信息录入表格
	 * @return
	 */
	@RequestMapping(value = "/add.do")
    public String add(ModelMap model){
		Product product = new Product();
		model.put("product", product);
		model.addAttribute("oss_bucketName", ossServiceImpl.getBucketName() );
		model.addAttribute("oss_endpoint", ossServiceImpl.getEndpoint() );
		
		return "product/product";
	}
	
	/**
	 * 产品信息编辑表格
	 * @return
	 */
	@RequestMapping(value = "/edit.do")
    public String edit(Long id, ModelMap model){
		Product product = productService.load(id);
		model.put("product", product);
		model.addAttribute("oss_bucketName", ossServiceImpl.getBucketName() );
		model.addAttribute("oss_endpoint", ossServiceImpl.getEndpoint() );
		
		List<ProductCategory> lsCategory = categoryService.list();
		model.addAttribute("lsCategory", lsCategory );
		
		return "product/product";
	}
	
	/**
	 * 保存客户信息到数据库
	 * @return
	 */
	@RequestMapping(value = "/save.do")
    @ResponseBody
    public ResponseObject<Product> save(Product product){
		User user = this.getCurrentUser();
    	
		try{
			if(product.getId() == null){
				ProductSearchForm form = new ProductSearchForm();
				form.setProductNo( new String[]{product.getNo()} );
				int count = productService.countProduct(form);
				if(count >0)
					throw new BizException(GlobalErrorCode.INTERNAL_ERROR, "产品编号重复");
				
				productService.insert(user, product);
			}else{
				productService.update(user, product);
			}
		}catch(Exception e){
			logger.error("",e);
			throw e;
		}
		return new ResponseObject<>(product);
	}
	
	/**
	 * 删除商品信息
	 * @return
	 */
	@RequestMapping(value = "/delete.do")
    @ResponseBody
    public ResponseObject<Integer> delete(Long id){
		User user = this.getCurrentUser();
		
		int count = 0;
		count = productService.delete(user, id);
		
		return new ResponseObject<Integer>(count);
	}
	
	/**
	 * 导入客户信息--界面
	 * @return
	 */
	@RequestMapping(value = "/export.do")
    @ResponseBody
    public void exportProduct(HttpServletRequest request, HttpServletResponse response,ProductSearchForm form){
		
		Workbook workbook = null;
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");				
		String fileName = "商品导出" + sdf.format(new java.util.Date()) + ".xls";		
		try{
			workbook = productService.exportProducts(form);
			fileName = new String(fileName.getBytes("utf-8"),"iso8859-1");
			
			response.setHeader("Content-Disposition", "attachment; filename=\""
					+ fileName + "\"");
			response.setContentType("application/octet-stream; charset=UTF-8");
			
			java.io.OutputStream os = response.getOutputStream();
			workbook.write(os);
			os.flush();
			os.close();
			
			workbook.close();
		}catch(Exception e){
			logger.error("", e);
		}
	}
	
	/**
	 * 导入客户信息--界面
	 * @return
	 */
	@RequestMapping(value = "/import.do")
    public String importProduct(ModelMap model){
		User user = this.getCurrentUser();
		model.addAttribute("user", user);
		
		return "product/importProduct";
	}
	
	/**
	 * 录入客户信息到数据库
	 * @return
	 */
	@RequestMapping(value = "/doImport.do")
    public String doImport(@RequestParam(value = "file") MultipartFile file, 
    		HttpServletRequest request, ModelMap model){
		User user = this.getCurrentUser();
		model.addAttribute("user", user);
		
		String webRootPath = request.getServletContext().getRealPath("/");
		
		String fileName = (file==null)?null:file.getOriginalFilename().toLowerCase();
		if (fileName ==null ) {
			model.addAttribute("msg", "请选择上传文件");
		}else if (!fileName.endsWith(".xls") && !fileName.endsWith(".xlsx")) {
			model.addAttribute("msg", "只支持excel文件格式");
		}
		else{
			//导入数量
			int count = 0;
			
			try{
				count = productService.importProduct(user, webRootPath, file);				
			} catch (BizException e) {
				getLogger().error("", e);
				throw e;
			} catch (Exception e) {
				getLogger().error("", e);
				throw new BizException(GlobalErrorCode.INTERNAL_ERROR,
						e.getMessage());
			}
			
			model.addAttribute("count", count);
			model.addAttribute("msg", "导入成功");
		}
		
		return "product/importProduct";
	}
	
	/**
	 * 上传的图片信息
	 * @return
	 */
	@RequestMapping(value = "/delUploadedImage.do")
    @ResponseBody
    public ResponseObject<Boolean> delUploadedImage(HttpServletRequest request, String fileName){
		User user = this.getCurrentUser();
		
		Boolean bFlag = false;
		Map<String,Object> map = new java.util.HashMap<String, Object>();
		String webRootPath = request.getServletContext().getRealPath("/");
		String filePath = productService.getUploadedImagePath(webRootPath) ;
		
		File file = new File(filePath);
		if(file.exists()){
			File f = new File(filePath, fileName);
			if(f.exists() && !f.isDirectory()){
				f.delete();
				bFlag = true;
			}
		}
		
		return new ResponseObject<>(bFlag);
	}
	
	/**
	 * 上传的图片信息
	 * @return
	 */
	@RequestMapping(value = "/uploadedImageData.do")
    @ResponseBody
    public Map<String, Object> uploadedImageData(HttpServletRequest request){
		User user = this.getCurrentUser();

		Map<String,Object> map = new java.util.HashMap<String, Object>();
		String webRootPath = request.getServletContext().getRealPath("/");
		String filePath = productService.getUploadedImagePath(webRootPath) ;
		
		File file = new File(filePath);
		List<UploadedImage> lsImage = new ArrayList<>();
		
		if(file !=null && file.isDirectory()){
			for(File f:file.listFiles()){
				if(f.isDirectory())
					continue;
				
				UploadedImage img = new UploadedImage();
				img.setName(f.getName());
				img.setLength(f.length());
				img.setUploadedAt( new Date(f.lastModified()) ); 
				lsImage.add(img);
			}
		}
		
		map.put("total", lsImage.size());
		map.put("rows", lsImage);
		
		return map;
	}
	
	/**
	 * 客户管理
	 * @return
	 */
	@RequestMapping(value = "/uploadedImages.do")
    public String uploadedImages(HttpServletRequest request,ModelMap model){
		User user = this.getCurrentUser();		
		
		String webRootPath = request.getServletContext().getRealPath("/");
		String filePath = productService.getUploadedImagePath(webRootPath) ;
		
		File file = new File(filePath);
		List<UploadedImage> lsImage = new ArrayList<>();
		
		if(file !=null && file.isDirectory()){
			for(File f:file.listFiles()){
				if(f.isDirectory())
					continue;
				
				UploadedImage img = new UploadedImage();
				img.setName(f.getName());
				img.setLength(f.length());
				img.setUploadedAt( new Date(f.lastModified()) ); 
				lsImage.add(img);
			}
		}
		
		model.put("files", lsImage);
		
		return "product/uploadedImages";
	}
	
	/**
	 * 录入客户信息到数据库
	 * @return
	 */
	@RequestMapping(value = "/uploadImage.do")
    public String uploadImage(@RequestParam(value = "file") MultipartFile[] files, 
    		HttpServletRequest request, ModelMap model) throws IOException{
		User user = this.getCurrentUser();
		model.addAttribute("user", user);
		
		String webRootPath = request.getServletContext().getRealPath("/");
				
		String filePath = productService.getUploadedImagePath(webRootPath) ;
		
		
				
		for (MultipartFile file : files) {
			File f= new java.io.File(filePath, file.getOriginalFilename());
			FileOutputStream fos = null;
			
			try{
				fos = new FileOutputStream(f);
				fos.write(file.getBytes());
				fos.flush();
			}catch(Exception e){
				
			}finally{
				if(fos !=null) fos.close();
			}
		}
		
		return "product/uploadedImages";
	}
}
